// Package crons
// @Link  https://github.com/bufanyun/hotgo
// @Copyright  Copyright (c) 2023 HotGo CLI
// @Author  Ms <133814250@qq.com>
// @License  https://github.com/bufanyun/hotgo/blob/master/LICENSE
package crons

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/gogf/gf/v2/os/gtime"
	"github.com/gogf/gf/v2/util/gconv"
	"hotgo/internal/library/cron"
	"hotgo/internal/model/entity"
	"hotgo/internal/model/input/sysin"
	"hotgo/internal/service"
	"hotgo/utility/client"
	"hotgo/utility/tradeDate"
	"io"
	"strings"
	"time"
)

func init() {
	cron.Register(AbnormalPool)
}

// AbnormalPool 测试任务（无参数）
var AbnormalPool = &cAbnormalPool{name: "abnormal_pool"}
var AbnormalPoolUrls = map[string]string{
	"强势股": "http://127.0.0.1:8000/api/public/stock_zt_pool_strong_em",
	"次新":  "http://127.0.0.1:8000/api/public/stock_zt_pool_sub_new_em",
	"炸板":  "http://127.0.0.1:8000/api/public/stock_zt_pool_zbgc_em",
}

type AbnormalPoolResp struct {
	Code           string `json:"代码"`
	Name           string `json:"名称"`
	NewHigh        int    `json:"是否新高"`
	ZBCS           int    `json:"炸板次数"`
	ZtStatistics   string `json:"涨停统计"`
	LBNumber       int    `json:"连板数"`
	SelectedReason int    `json:"入选理由"`
	Industry       string `json:"所属行业"`
	StartDate      string `json:"上市日期"`
}
type cAbnormalPool struct {
	name string
}

func (c *cAbnormalPool) GetName() string {
	return c.name
}

// Execute 执行任务
func (c *cAbnormalPool) Execute(ctx context.Context, parser *cron.Parser) (err error) {
	date := tradeDate.GetLatestDay()
	parse, _ := time.Parse(time.DateOnly, date)
	formatDate := gtime.New(parse).Format("Ymd")
	httpClient := client.GetClient()
	for source, AbnormalPoolUrl := range AbnormalPoolUrls {
		response, err := httpClient.Get(ctx, fmt.Sprintf("%s?date=%s", AbnormalPoolUrl, formatDate))
		if err != nil {
			parser.Logger.Warning(ctx, "cron CloseOrder Execute http.Get err:%+v", err)
			continue
		}
		defer response.Body.Close()
		body, err := io.ReadAll(response.Body)
		if err != nil {
			parser.Logger.Warning(ctx, "cron CloseOrder Execute io.ReadAll err:%+v", err)
			continue
		}
		var resp []AbnormalPoolResp
		err = json.Unmarshal(body, &resp)
		if err != nil {
			parser.Logger.Warning(ctx, "cron CloseOrder Execute json.Unmarshal err:%+v", err)
			continue
		}
		abnormalType := 0
		switch source {
		case "强势股":
			abnormalType = 1
		case "次新":
			abnormalType = 2
		case "炸板":
			abnormalType = 3
			var delInp = &sysin.StockAbnormalPoolDeleteInp{
				Type: abnormalType,
				Date: date,
			}
			service.SysStockAbnormalPool().Delete(ctx, delInp)
		}
		// 删除对应数据
		for _, emResp := range resp {
			ZtStatistics := strings.Split(emResp.ZtStatistics, "/")

			ztStatisticsDays := 0
			ztStatisticsNum := 0
			if len(ZtStatistics) == 2 {
				ztStatisticsDays = gconv.Int(ZtStatistics[0])
				ztStatisticsNum = gconv.Int(ZtStatistics[1])
			}

			err := service.SysStockAbnormalPool().Edit(ctx, &sysin.StockAbnormalPoolEditInp{
				StockAbnormalPool: entity.StockAbnormalPool{
					Code:             emResp.Code,
					Name:             emResp.Name,
					Date:             date,
					Zbcs:             emResp.ZBCS,
					LbNumber:         emResp.LBNumber,
					ZtStatisticsDays: ztStatisticsDays,
					ZtStatisticsNum:  ztStatisticsNum,
					Industry:         emResp.Industry,
					Type:             abnormalType,
					NewHigh:          emResp.NewHigh,
					SelectedReason:   emResp.SelectedReason,
					StartDate:        emResp.StartDate,
				},
			})
			if err != nil {
				parser.Logger.Warning(ctx, "cron CloseOrder Execute service.SysStockZhASpotEm().Edit err:%+v", err)
				continue
			}
		}
	}
	return
}
